package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.context.LoginUserContext;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SmsService smsService;
    @Autowired
    private UserInfoService userInfoService;

    //    获取验证码
    @Override
    public void getMessage(String phone) {
//        没有输入手机号  没法获取验证码
        if (!StringUtils.hasLength(phone)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }

//        往redis里存的时候的key  自己定义即可
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;

//        redis中查询是否存在此key  不存在才需要生成新的存进去
        if (stringRedisTemplate.hasKey(key)) {
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }

        //生成验证码   此处自己写了一个工具类来生成六位的随机数字  也可以使用easy-captcha生成
//        使用easy-captcha生成的代码如下
//        SpecCaptcha specCaptcha = new SpecCaptcha(130,48,6);
//        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
//        String result = specCaptcha.text().toLowerCase();

        String code = VerifyCodeUtil.getVerifyCode(6);
        //发送验证码
        smsService.sendCode(phone, code);
        System.out.println("验证码:" + code);
        //保存到redis中
        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.DAYS);
    }

    @Override
    public String login(LoginVo loginVo) {

        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        //1. 校验是否有验证码存在
        if (!StringUtils.hasLength(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        if (!StringUtils.hasLength(loginVo.getPhone())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
            //2.检验验证码是否正确
            String code = loginVo.getCode();
            if (!code.equals(stringRedisTemplate.opsForValue().get(key))) {
                throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
            }

            //3.验证码发送是否过于频繁
            if (!stringRedisTemplate.hasKey(key)) {
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }

//        此时查找是否有此用户 没有的话注册用户
            LambdaQueryWrapper<UserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
            UserInfo info = userInfoService.getOne(lambdaQueryWrapper);

            if (info == null) {
//                没有用户 注册
                info = new UserInfo();

                info.setAvatarUrl("http://192.168.126.128:9000/lease/2024/09/0cb300ccd108406eb3446ed8b6e63cee.jpg");
                info.setNickname("公寓-" + loginVo.getPhone());
                info.setStatus(BaseStatus.ENABLE);
                info.setPhone(loginVo.getPhone());

                userInfoService.save(info);
            }
//            有此用户 查看用户状态
            if (info.getStatus() == BaseStatus.DISABLE){
                throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
            }

//            全部信息都正确  返回token
            String token = JwtUtil.createToken(info.getId());
//            在ThreadLocal中加入用户信息  方便后续获取用户信息展示
            return token;

    }
}
